package com.suncky.frame.utils.image;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;

import androidx.annotation.NonNull;

import java.lang.ref.WeakReference;
import java.util.concurrent.Executor;

/**
 * @author gl
 */
public class MainThreadExecutor implements Executor {
    private final Handler handler;
    private final WeakReference<Context> weakContextReference;

    public MainThreadExecutor(Context context) {
        handler=new Handler(Looper.getMainLooper());
        weakContextReference = new WeakReference<>(context);
    }

    @Override
    public void execute(@NonNull Runnable r) {
        Context context = weakContextReference.get();
        if (context == null || (context instanceof Activity && ((Activity) context).isFinishing())) {
            return;
        }
        handler.post(r);
    }

    public void executeDelayed(@NonNull Runnable r, long millisecond) {
        Context context = weakContextReference.get();
        if (context == null || (context instanceof Activity && ((Activity) context).isFinishing())) {
            return;
        }
        handler.postDelayed(r, millisecond);
    }

    public void removeCallbacks(Object token) {
        handler.removeCallbacksAndMessages(token);
    }
}
